package com.mall507.fivepeaks.activity.find;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.google.gson.Gson;
import com.hzh.frame.comn.ItemDecoration.BaseGridSpacingItemDecoration;
import com.hzh.frame.comn.annotation.ViewInject;
import com.hzh.frame.comn.callback.HttpCallBack;
import com.hzh.frame.core.HttpFrame.BaseHttp;
import com.hzh.frame.ui.activity.BaseUI;
import com.hzh.frame.util.AndroidUtil;
import com.hzh.frame.util.StatusBarUtil;
import com.hzh.frame.widget.xdialog.XDialog1Button;
import com.hzh.frame.widget.xrecyclerview.BaseRecyclerAdapter;
import com.hzh.frame.widget.xrecyclerview.RecyclerViewHolder;
import com.mall507.comn.matisse.GifSizeFilter;
import com.mall507.comn.model.UploadImage;
import com.mall507.comn.tools.UserTools;
import com.mall507.fivepeaks.R;
import com.mall507.fivepeaks.activity.mine.FeedBackUI;
import com.mall507.fivepeaks.util.ImageUtil;
import com.mall507.fivepeaks.util.UriUtil;
import com.mall507.fivepeaks.util.Util;
import com.mall507.fivepeaks.widget.xdialog.XMineChooseDialog;
import com.mall507.fivepeaks.widget.xdialog.XRadioGroupDialog;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropActivity;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.PicassoEngine;
import com.zhihu.matisse.filter.Filter;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Route(path = "/find/FindLostWriteUI")
public class FindLostWriteUI extends BaseUI {
    private static final int REQUEST_IMAGE = 1;// 图片选择
    private static final int REQUEST_CROP = 2;// 图片剪裁
    
    @ViewInject(R.id.write)
    EditText write;
    @ViewInject(R.id.content)
    EditText content;
    @ViewInject(R.id.writeNumber)
    TextView writeNumber;
    @ViewInject(R.id.contentNumber)
    TextView contentNumber;
    @ViewInject(R.id.submit) 
    Button submit;
    @ViewInject(R.id.classify)
    TextView classify;
    @ViewInject(R.id.image_upload_recyclerView)
    RecyclerView imageUploadRecyclerView;

    List<HashMap<String, Object>> areaList = new ArrayList<>();
    
    @Override
    protected void onCreateBase() {
        setContentView(R.layout.ui_find_lostwrite);
        getTitleView().setContent("遗失填写");
        String[] writeType = {"失物招领","寻物启事","寻人启事"};
        write.setHorizontallyScrolling(true);
        initImageUploadGridview();
        for (int i = 0;i<writeType.length;i++){
            HashMap<String, Object> map = new HashMap<>();
            map.put("name",writeType[i]);
            map.put("value",i+1);
            areaList.add(map);
            if(i==0){//设置默认值,默认第一个为需要请求的值
                classify.setText(writeType[i]);
                classify.setTag(R.id.main_release_lostwrite_value, i+1);
            }
        }
        write.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                writeNumber.setText(s.length() + "/7");
            }
        });

        content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                contentNumber.setText(s.length() + "/99");
            }
        });
        
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uploadImage();
            }
        });
        
        classify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new XRadioGroupDialog().show(FindLostWriteUI.this, areaList, new XRadioGroupDialog.IRadioGroupDialogCallBack() {
                    @Override
                    public void confirm(HashMap<String, Object> selectedItem) {
                        classify.setText(selectedItem.get("name").toString());
                        classify.setTag(R.id.main_release_lostwrite_value, selectedItem.get("value").toString());
                    }

                    @Override
                    public void cancel() {

                    }
                });
            }
        });
    }

    private void uploadImage() {
        if (TextUtils.isEmpty(write.getText()) || TextUtils.isEmpty(content.getText())) {
            alert("输入标题以及具体内容才可以发布");
        } else {
            if (content.getText().toString().length() < 10){
                alert("内容字数不足10字");
            }else {
                final ArrayList<String> image = new ArrayList<>();
                List<HashMap<String,Object>> fileList=new ArrayList<>();
                FindLostWriteUI.ItemAdapter adapter= (FindLostWriteUI.ItemAdapter) imageUploadRecyclerView.getAdapter();
                List<UploadImage> list = adapter.getDatalist();
                for(int i=0;i<list.size();i++){
                    UploadImage model=list.get(i);
                    if (!Util.isEmpty(model.getUri())) {
                        HashMap<String,Object> map = new HashMap<>();
                        map.put("name","Image"+i);
                        map.put("file",new File(model.getUri()));
                        fileList.add(map);
                    }
                }
                if (fileList.size()>0){
                    BaseHttp.getInstance().uploadFile(FindLostWriteUI.this,"upload/image",fileList, new HttpCallBack() {
                        @Override
                        public void onSuccess(JSONObject response) {
                            if (response.optInt("code") == 200) {
                                JSONArray url = response.optJSONArray("url");
                                if (url != null&&url.length()>0){
                                    for (int i = 0;i<url.length();i++){
                                        JSONObject object = url.optJSONObject(i);
                                        image.add(object.optString("val"));
                                    }
                                }
                                submit(image);
                            }else{
                                alert(response.optString("msg"));
                            }
                        }
                    });
                }else {
                    submit(image);
                }
            }
        }
    }
    
    public void initImageUploadGridview() {
        imageUploadRecyclerView.setLayoutManager(new GridLayoutManager(this,5));
        imageUploadRecyclerView.addItemDecoration(new BaseGridSpacingItemDecoration(this,5,0));
        List<UploadImage> resourceList = new ArrayList<>();
        resourceList.add(new UploadImage());
        imageUploadRecyclerView.setAdapter(new FindLostWriteUI.ItemAdapter(this,resourceList));
    }

    protected void submit(ArrayList<String> array) {
        JSONObject params = new JSONObject();
        try {
            params.put("title", write.getText().toString());
            params.put("desc", content.getText().toString());
            params.put("type",classify.getTag(R.id.main_release_lostwrite_value).toString());
            if(array.size()>0){
                params.put("image",array);
                params.put("thum",array.get(0).toString());
            }else {
                params.put("thum","");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        BaseHttp.getInstance().write("Explorer/lost", params, new HttpCallBack() {
            @Override
            public void onSuccess(JSONObject response) {
                if (response.optInt("code") == 200) {
                    write.getText().clear();
                    content.getText().clear();
                    initImageUploadGridview();
                    ARouter.getInstance().build("/release/ReleaseSuccessUI").navigation();
                }else {
                    alert(response.optString("msg"));
                }
            }
        });
    }

    private class ItemAdapter extends BaseRecyclerAdapter<UploadImage> {

        public ItemAdapter(Context ctx, List<UploadImage> list) {
            super(ctx, list);
        }

        @Override
        public int getItemLayoutId(int viewType) {
            return R.layout.item_gv_image_upload;
        }

        @Override
        public void bindData(RecyclerViewHolder holder, final int position, UploadImage item) {
            if (!Util.isEmpty(item.getUri())) {
                //正常显示图片
                ((ImageView) holder.getView(R.id.image)).setImageURI(Uri.parse(item.getUri()));
                ((ImageView) holder.getView(R.id.close)).setVisibility(View.VISIBLE);
                holder.getView(R.id.close).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        getDatalist().remove(position);
                        notifyDataSetChanged();
                    }
                });
                holder.setOnItemClickListener(null);
            } else {
                //显示添加图片按钮
                ((ImageView) holder.getView(R.id.image)).setImageResource(R.mipmap.comn_image_upload);
                ((ImageView) holder.getView(R.id.close)).setVisibility(View.GONE);
                holder.setOnItemClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        openCamera(view);
                    }
                });
            }
        }

        public List<UploadImage> getDatalist() {
            return super.getDatas();
        }
    }

    /**
     * 相机
     */
    public void openCamera(View view) {
        Matisse.from(this).choose(MimeType.ofImage()).theme(R.style.Matisse_Dracula)
                //                .countable(true)//有序选择图片 123456...
                .maxSelectable(1)//最大选择数量为1
                .countable(false).capture(true)//拍照
                .captureStrategy(new CaptureStrategy(true, AndroidUtil.getPackageName() + ".fileProvider"))//拍照
                .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K)).maxSelectable(9).originalEnable(true).maxOriginalSize(10).imageEngine(new PicassoEngine()).forResult(REQUEST_IMAGE);
    }

    /**
     * 启动裁剪
     *
     * @param activity  上下文
     * @param sourceUir 需要裁剪图片的Uri
     * @return
     */
    public void startUCrop(Activity activity, Uri sourceUir) {
        //裁剪后保存到文件中
        Uri destinationUri = Uri.fromFile(new File(getCacheDir(), System.currentTimeMillis() + ".jpg"));
        //初始化，第一个参数：需要裁剪的图片；第二个参数：裁剪后图片
        UCrop uCrop = UCrop.of(sourceUir, destinationUri);
        UCrop.Options options = new UCrop.Options();//初始化UCrop配置
        options.setCompressionFormat(Bitmap.CompressFormat.JPEG);//设置剪裁出来的是JPEG格式的图片
        options.setCircleDimmedLayer(false);//设置是否展示圆形剪裁框
        options.setShowCropFrame(true);//设置是否展示矩形剪裁框
        options.setShowCropGrid(true);//设置是否展示网格剪裁框
        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);//设置裁剪图片可操作的手势 缩放、旋转、剪裁,none就是不设置
        //        options.setToolbarColor(ActivityCompat.getColor(activity, R.color.dracula_primary));//设置toolbar颜色
        options.setStatusBarColor(ActivityCompat.getColor(activity, R.color.application_color));//设置状态栏颜色
        //        options.setHideBottomControls(true);//是否隐藏底部容器，默认显示
        options.setFreeStyleCropEnabled(true);//是否能调整裁剪图片的宽高比
        uCrop.withOptions(options);
        //        uCrop.withAspectRatio(1, 1);//设置裁剪图片的宽高比，比如16：9（设置后就不能选择其他比例了、选择面板就不会出现了）
        uCrop.start(activity, REQUEST_CROP);
        StatusBarUtil.setBlackIcon(this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        StatusBarUtil.setWhileIcon(this);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_IMAGE:// 图片选择
                    if (resultCode == -1) {//-1:确定 0:取消
                        List<Uri> imageUris = Matisse.obtainResult(data);
                        if (imageUris != null && imageUris.size() > 0) {
                            startUCrop(this, imageUris.get(0));
                        }
                    }
                    break;
                case REQUEST_CROP:// 裁剪图片
                    setImage(UCrop.getOutput(data));
                    break;
            }
        }
    }

    private Bitmap headBitmap;//头像
    private Uri localHead;

    public void setImage(Uri uri) {
        localHead = uri;
        headBitmap = BitmapFactory.decodeFile(UriUtil.getRealFilePath(this, uri), getBitmapOption(1)); //将图片的长和宽缩小味原来的1/2
        headBitmap = ImageUtil.Bytes2Bimap(ImageUtil.zoom(headBitmap, 200));

        FindLostWriteUI.ItemAdapter itemAdapter = (FindLostWriteUI.ItemAdapter) imageUploadRecyclerView.getAdapter();
        List<UploadImage> list = itemAdapter.getDatalist();
        UploadImage model = new UploadImage();
        model.setUri(UriUtil.getRealFilePath(this, uri));
        list.add(list.size()-1, model);
        itemAdapter.notifyDataSetChanged();
    }

    private BitmapFactory.Options getBitmapOption(int inSampleSize) {
        System.gc();
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPurgeable = true;
        options.inSampleSize = inSampleSize;
        return options;
    }
    
    
}
